package com.example.my

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.activity.ComponentActivity
import android.widget.Button
import android.widget.TextView
class FifthActivity : ComponentActivity() {
    var seconds = 0
    var running = false
    var wasRunning = false
    private lateinit var textViewTimer: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_fifth)

        val buttonStart = findViewById<Button>(R.id.button_start)
        val buttonStop = findViewById<Button>(R.id.button_stop)
        val buttonRestart = findViewById<Button>(R.id.button_restart)
        textViewTimer = findViewById(R.id.textView_timer)

        if(savedInstanceState != null){
            seconds=savedInstanceState.getInt("seconds")
            running=savedInstanceState.getBoolean("running")
            wasRunning=savedInstanceState.getBoolean("wasRunning")
        }

        runTimer()
        buttonStart.setOnClickListener {
            running = true
        }
        buttonStop.setOnClickListener {
            running = false
        }
        buttonRestart.setOnClickListener {
            running = true
            seconds = 0
        }
    }

    fun runTimer() {
        val handler = Handler(Looper.getMainLooper())

        val runnable = object : Runnable {
            override fun run() {
                val hours = seconds / 3600
                val minutes = (seconds % 3600) / 60
                val secs = seconds % 60
                // 格式化为 HH:MM:SS
                textViewTimer.text = String.format("%02d:%02d:%02d", hours, minutes, secs)
                if (running) {
                    seconds++
                }
                handler.postDelayed(this, 1000)// 每隔 1000ms (1秒) 再次调用自己
            }
        }
        handler.post(runnable)// 启动定时器：第一次调用 runnable
    }


    override fun onSaveInstanceState(outState: Bundle){
        super.onSaveInstanceState(outState)
        Log.d( "Life cycle","onSaveInstanceState")
        outState.putInt("seconds",seconds)
        outState.putBoolean("running",running)
        outState.putBoolean("wasRunning",wasRunning)
    }

}